package org.budo.netty.servlet.server.servlet;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.budo.netty.servlet.server.handler.servlet.BudoServletRequest;
import org.budo.netty.servlet.util.RequestUtil;
import org.budo.netty.servlet.util.ResponseUtil;

/**
 * @author li
 */
public class DefaultServlet extends HttpServlet {
    private static final long serialVersionUID = -7988332205625396384L;

    public static final DefaultServlet INSTANCE = new DefaultServlet();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String requestURI = request.getRequestURI();

        InputStream inputStream = request.getServletContext().getResourceAsStream(requestURI);
        if (null != inputStream) {
            ResponseUtil.write(response, inputStream);
            return;
        }

        this.resourceNotFound(request, response);
    }

    private void resourceNotFound(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String requestURI = request.getRequestURI();
        BudoServletRequest budoServletRequest = RequestUtil.getBudoServletRequest(request);

        if ("/".equals(requestURI)) { // index
            InputStream welcomeFile = this.findWelcomeFile(budoServletRequest);
            if (null != welcomeFile) {
                ResponseUtil.write(response, welcomeFile);
                return;
            }
        }

        response.setStatus(404);
        ResponseUtil.write(response, "<h1>404 " + requestURI + "</h1>");
    }

    private InputStream findWelcomeFile(BudoServletRequest budoServletRequest) {
        List<String> welcomeFileList = budoServletRequest.getBudoServletHandler().getBudoServletServer().getWelcomeFileList();
        for (String welcomeFile : welcomeFileList) { // welcomeFileList
            InputStream resource = budoServletRequest.getServletContext().getResourceAsStream(welcomeFile);
            if (null != resource) {
                return resource;
            }
        }

        return null;
    }
}